import React, { useRef, useEffect } from 'react';
import * as echarts from 'echarts';
import { useSize } from 'ahooks';

export default ({ style = {}, option = null }) => {
  const chartIns = useRef();
  const chartRef = useRef(null);
  const chartSize = useSize(chartRef);

  useEffect(() => {
    // 创建图表
    chartIns.current =
      echarts.getInstanceByDom(chartRef?.current) || echarts.init(chartRef?.current);
  }, [chartRef]);

  useEffect(() => {
    // 响应式
    if (!chartSize?.width) return;
    chartIns.current?.resize();
  }, [chartSize]);

  useEffect(() => {
    if (!option) return;
    chartIns.current?.setOption(option, true); // 更新视图
  }, [JSON.stringify(option)]);

  return (
    <div
      ref={chartRef}
      style={{
        width: '100%',
        height: '100%',
        ...style,
      }}
    />
  );
};
